import json

import facade
from xjlibrary.mdatetime.mtime import MDateTime
from xjlibrary.our_file_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")
topPath = BaseDir.get_upper_dir(curPath, -2)
sPath = BaseDir.get_new_path(topPath, "download", "bookan_shichuan", "download", "issue")
BaseDir.create_dir(sPath)


class DownIssue(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutil = facade.MysqlUtiles(configfile, "db", logger=self.logger)
        self.header = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Host": "user.bookan.com.cn",
            "Pragma": "no-cache",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
        }

    def down_one_issue(self, issueid):
        """
        下载具体某一期
        :return:
        """
        dicts = {}
        url = "http://user.bookan.com.cn/index.php?op=Resource.catalogInfo&resourceType=1&categoryId={}&statusType=1".format(
            issueid)
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      endstring="",
                                                      headers=self.header,
                                                      timeout=(30, 60),
                                                      mark="id"
                                                      )
        if BoolResult:
            jsondicts = json.loads(r.text)
            dicts["article"] = jsondicts
        else:
            print("下载期刊信息出错 这是有可能的")
            return False
        url = "http://user.bookan.com.cn/index.php?op=Resource.issueInfoList&resourceType=1&issueIds={}&isFree=0&isDetail=1&instanceId=21635".format(
            issueid)
        del BoolResult, errString, r
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      endstring="",
                                                      headers=self.header,
                                                      timeout=(30, 60),
                                                      mark="resourceType"
                                                      )
        if BoolResult:
            jsondicts = json.loads(r.text)
            dicts["bookmsg"] = jsondicts
        else:
            print("下载期刊信息出错")
            return False
        dicts["downdate"] = MDateTime().get_today_date()
        jsonmsg = json.dumps(dicts, ensure_ascii=False)
        filepath = BaseDir.get_new_path(sPath, MDateTime().get_today_date() + ".big_json")
        BaseDir.single_add_file(filepath, jsonmsg + "\n")
        return True

    def task(self):
        while True:
            sql = "select issueid  from issue where stat=0 and failcount<3 limit 1000"
            rows = self.mysqlutil.SelectFromDB(sql)
            if rows:
                for row in rows:
                    boolresult = self.down_one_issue(row[0])
                    if boolresult:
                        sql = "update issue set stat=1 where issueid='{}'".format(row[0])
                        self.mysqlutil.ExeSqlToDB(sql)
                    else:
                        sql = "update issue set failcount=failcount+1 where issueid='{}'".format(row[0])
                        self.mysqlutil.ExeSqlToDB(sql)
            else:
                break


def main():
    down = DownIssue()
    down.task()


if __name__ == "__main__":
    main()
